package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MySQLRaavareDAO implements RaavareDAO {

	private Connector conn = null;
	private ResultSet rs = null;

	public MySQLRaavareDAO() throws DALException {
		conn = new Connector();
	}
	
	public RaavareDTO getRaavare(int raavareId) throws DALException {

		
		RaavareDTO rVare = null;

		String query = "SELECT * FROM raavare WHERE raavareId = " + raavareId
				+ ";";
		rs = conn.doQuery(query);
		try {
			if (!rs.first()) {
				throw new DALException("Operatoeren med " + raavareId
						+ " findes ikke");
			}
			rVare = new RaavareDTO(rs.getInt(1), rs.getString(2),
					rs.getString(3));
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return rVare;
	}

	public ArrayList<RaavareDTO> getRaavareList() throws DALException {

		ArrayList<RaavareDTO> rVare = new ArrayList<RaavareDTO>();
		String query = "SELECT * FROM raavare";
		rs = conn.doQuery(query);

		try {
			while (rs.next()) {
				rVare.add(new RaavareDTO(rs.getInt(1), rs.getString(2), rs
					.getString(3)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rVare;

	}
	public List<RaavareDTO> getRaavareList(int first, int count) throws DALException {

		List<RaavareDTO> raavare = new ArrayList<RaavareDTO>();
		String query = "SELECT * FROM raavare LIMIT " + first + "," + count;
		rs = conn.doQuery(query);

		try {
			while (rs.next()) {
				raavare.add(new RaavareDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return raavare;
	}
	
	public int getCount() throws DALException {
		rs = conn.doQuery("SELECT COUNT(raavareId) FROM raavare");
		try {
			if (rs.next())
				return rs.getInt(1);
			else
				return 0;
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public void createRaavare(RaavareDTO raavare) throws DALException {
		conn.doUpdate("INSERT INTO raavare (raavareNavn, leverandoer) VALUES "
				+ "('"
				+ raavare.getRaavareNavn()
				+ "', '"
				+ raavare.getLeverandoer()
				+ "')");

	}

	public void updateRaavare(RaavareDTO raavare) throws DALException {
		if (conn == null)
			conn = new Connector();
		conn.doUpdate("UPDATE raavare SET  raavareId = "
				+ raavare.getRaavareId() + ", raavareNavn =  '"
				+ raavare.getRaavareNavn() + "', leverandoer = '"
				+ raavare.getLeverandoer() + "' WHERE raavareId = "
				+ raavare.getRaavareId());

	}

}
